package com.example.demo2.common.api;

import com.example.demo2.common.check.CheckError;
import com.google.common.base.Throwables;

public class LqApiError {
    private int code;
    private String msg;
    private String debugMessage;
    // private Date responseTime = new Date();
    private String trace;

    private LqApiError() {
    }

    public static LqApiError from(CheckError error, boolean debug) {
        Builder result = LqApiError.builder();
        result.code(error.getCode());
        result.msg(error.getMsg());
        result.cause(error.getCause());
        result.debugMessage(error.getDebugMessage());

        return result.build(debug);
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public String getDebugMessage() {
        return debugMessage;
    }

    public String getCause() {
        return trace;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {
        private Throwable cause;
        private int code;
        private String debugMessage;
        private String msg;

        private Builder() {
        }

        public LqApiError build(boolean debug) {
            LqApiError result = new LqApiError();
            result.code = code;
            result.msg = msg;
            if (debug) {
                result.debugMessage = debugMessage;
                result.trace = cause == null ? null : Throwables.getStackTraceAsString(cause);
            }
            return result;
        }

        public Builder code(int code) {
            this.code = code;
            return this;
        }

        /**
         * Check#code为i18n objectErrors，可以用此方法设置message中的参数.
         */
        public Builder msg(String msg) {
            this.msg = msg;
            return this;
        }

        /**
         * Fail#debugMessage.
         */
        public Builder debugMessage(String message) {
            this.debugMessage = message;
            return this;
        }

        public Builder cause(Throwable e) {
            this.cause = e;
            return this;
        }
    }
}
